package main

import (
	"fmt"
	"net"
	"os"
	"sync"
)

// const addr = "127.0.0.1:8000"
var addr string

func init() {
	file, err := os.Open("config.txt")
	if err != nil {
		panic("缺少配置文件，请在当前目录添加config.txt，内容为服务器地址，例如：127.0.0.1:8000")
	}
	buf := make([]byte, 1024)
	n, err := file.Read(buf)
	addr = string(buf[:n])
}

func main() {
	//获取命令行参数
	list := os.Args

	if len(list) < 2 {
		fmt.Printf("用法\nclient list\nclient upload xxx ...\nclient download xxx ...")
		return
	}
	fmt.Println(addr)
	conn, err := net.Dial("tcp", addr)
	if err != nil {
		fmt.Println("连接出错")
	}
	defer conn.Close()
	wg := &sync.WaitGroup{}
	//获取操作命令
	flag := list[1]
	if flag == "list" {
		conn.Write([]byte("list"))
		buf := make([]byte, 4096)
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Printf("conn.Read(buf)方法执行出错，错误为:%v\n", err)
		}
		fmt.Printf("file list:\n%s", buf[:n])
	} else if flag == "upload" {
		files := list[2:]
		for _, file := range files {
			wg.Add(1)
			go func(file string, wg *sync.WaitGroup) {
				defer wg.Done()
				Upload(file, addr)
			}(file, wg)
			// go Upload(file, addr)
		}
	} else if flag == "download" {
		files := list[2:]
		for _, file := range files {
			wg.Add(1)
			go func(file string, wg *sync.WaitGroup) {
				defer wg.Done()
				Download(file, addr)
			}(file, wg)
			// go Download(file, addr)
		}
	}
	// time.Sleep(2 * time.Second)
	wg.Wait()
}
